from setux.core.package import CommonPackager
from setux.targets import Local
from setux.logger import info, error


# pylint: disable=no-member


class Distro(CommonPackager):
    manager = 'guix'

    pkgmap = dict(
        kicad    = 'org.kicad_pcb.KiCad',
        freecad  = 'org.freecadweb.FreeCAD',
        openscad = 'org.openscad.OpenSCAD',
    )

    def do_init(self):
        ret, out, err = self.run('guix --version')
        if ret==0: return
        self.target.download(
            url = 'https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh',
            dst = '/tmp/guix-install.sh',

        )
        self.target.script('''
            cd /tmp
            chmod 777 guix-install.sh
            ./guix-install.sh
            guix install recsel
        ''')

    def do_install(self, pkg, ver=None):
        ret, out, err = self.run(f'guix install {pkg}')

    def do_installed(self, pattern=None):
        ret, out, err = self.run('guix package --list-installed')
        for n, v in out:
            yield n , v

    def do_installable_cache(self):
        # ret, out, err = self.run(f'guix search {pkg} | recsel -p name,version')
        ret, out, err = self.run(
            'guix package --list-available',
            report = 'quiet',
        )
        if ret!=0:
            error('\n'.join(out))
            return

        with open(self.cache_file, 'w') as pkg:
            for line in out:
                app, ver, *_ = line.split('\t')
                pkg.write(f'{app} {ver}\n')

    def do_remove(self, pkg):
        self.run(f'guix remove {pkg}')

    def do_cleanup(self):
        pass

    def do_update(self):
        pass

